# -*- coding: utf-8 -*-
"""A Namespace describes a QPBuild Namespace. These entities are created by
polling the namespace server(s) and merging the results into the database.
"""

from sqlalchemy import *
from sqlalchemy.orm import mapper, relation
from sqlalchemy import Table, ForeignKey, Column
from sqlalchemy.types import Integer, Unicode

from abserver.model import DeclarativeBase, metadata, DBSession


# This is the association table for the many-to-many relationship between
# components and branches.
component_branch_table = Table('component_branch_mm', metadata,
                               Column('component_id', Integer, ForeignKey('component.component_id',
                                                                          onupdate="CASCADE", ondelete="CASCADE")),
                               Column('branch_id', Integer, ForeignKey('branch.branch_id',
                                                                       onupdate="CASCADE", ondelete="CASCADE"))
                               )

class Component(DeclarativeBase):
    """The Component entities are created by polling each of the Namespaces to find all
    the components defined in that namespace.
    """
    # table options
    __tablename__ = 'component'

    # columns
    component_id = Column(Integer, primary_key=True, autoincrement=True)
    component_name = Column(Unicode(64), unique=True, nullable=False)
    component_description = Column(Unicode())
    namespace_id = Column(Integer, ForeignKey('namespace.namespace_id'))

    # relationships
    namespace = relation('Namespace', backref='components')
    branches = relation('Branch', secondary=component_branch_table, backref='components')
    ## builds
    ## product
    ## buildviews

    def __init__(self, component_name, namespace, description=None):
        self.component_name = component_name
        self.namespace = namespace
        self.description = description


    @classmethod
    def get_component(cls, component_name, namespace='TRIG'):
        """Convenience getter or factory method."""
        c = DBSession.query(cls).filter(cls.component_name==component_name).first()
        if not c:
            from abserver.model import Namespace
            ns = Namespace.get_namespace(namespace)
            c = Component(component_name=component_name, namespace=ns)
            DBSession.add(c)
            print "Component created", component_name
        return c

    @classmethod
    def get(cls, component_id):
        c = DBSession.query(cls).filter(cls.component_id==component_id).first()
        return c

    def full_name(self):
        ns = self.namespace
        if ns:
            return '.'.join([ns.namespace_name, self.component_name])
        else:
            return self.component_name
